package com.kaifamiao.context;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 1、在Servlet中获得ServletContext实例
 *     ServletConfig#getServletContext()
 *     ServletRequest#getServletContext()
 *     HttpSession#getServletContext()
 *     在JSP中可以通过内置对象 application 来访问 ServletContext
 *
 * 2、操作ServletContext的属性
 *     Object getAttribute(String name);
 *     Enumeration<String> getAttributeNames();
 *     void setAttribute(String name, Object value);
 *     void removeAttribute(String name);
 */
@WebServlet("/counter")
public class CounterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        // 尝试从会话对象中获得名称是counter的属性值
        Long sessionCounter = (Long)session.getAttribute( "counter" );
        // 若未能从会话对象的属性中获得counter
        if( sessionCounter == null ) {
            sessionCounter = 0L; // 赋予初始值
        }
        // 将计数器增加一之后重新设置到会话对象的属性中
        session.setAttribute( "counter" , ++sessionCounter );
        out.printf( "<p>%d</p>\n", sessionCounter );

        // ServletContext application = request.getServletContext();
        // ServletContext application = session.getServletContext();
        ServletContext application = this.getServletContext();
        // 尝试从ServletContext对象中获得名称是counter的属性值
        Long appCounter = (Long)application.getAttribute( "counter" );
        // 若未能从ServletContext对象的属性中获得counter
        if( appCounter == null ) {
            appCounter = 0L; // 赋予初始值
        }
        // 将计数器增加一之后重新设置到ServletContext对象的属性中
        application.setAttribute( "counter" , ++appCounter );
        out.printf( "<p>%d</p>\n", appCounter );
    }
}
